﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace KeyRemapper
{
    public class Remapper
    {
        public bool Enabled { get; set; }
        public bool UseDynamicKeymap { get; private set; }

        public SortedList<Keys, Keys> Map { get; private set; }

        private KeyboardHook _hook;
        private Random _rnd;
        private object _sync = new object();

        public Remapper(KeyboardHook hook)
        {
            _hook = hook;
            
            _hook.OnKeyPressed += hook_OnKeyPressed;
        }
        ~Remapper()
        {
            _hook.OnKeyPressed -= hook_OnKeyPressed;
        }

        public void Update(bool useDynamicKeyMap, int seed)
        {
            lock (_sync)
            {
                if (!useDynamicKeyMap)
                {
                    Map = MapGenerator.Generate(seed);
                }
                else
                {
                    _rnd = new Random(seed);
                }

                UseDynamicKeymap = useDynamicKeyMap;
            }
        }

        private void hook_OnKeyPressed(Keys k, ref bool block)
        {
            if (block)
                return;

            lock (_sync)
            {
                if (Enabled && MapGenerator.ValidKeys.Contains(k))
                {
                    if (!UseDynamicKeymap && Map != null && Map.Count > 0)
                    {
                        if (Map.ContainsKey(k))
                        {
                            Debug.WriteLine("[Remapper][Static] " + k + " => " + Map[k]);
                            
                            block = true;

                            Keyboard.PressKey(Map[k]);
                        }
                    }
                    else
                    {
                        Keys replacement = MapGenerator.ValidKeys[(_rnd.Next(0, MapGenerator.ValidKeys.Count) + (int)k) % MapGenerator.ValidKeys.Count];

                        Debug.WriteLine("[Remapper][Dynamic] " + k + " => " + replacement);

                        block = true;

                        Keyboard.PressKey(replacement);
                    }
                }
            }
        }
    }
}
